<script lang="ts" setup>
import type { Recordable } from '@vben/types';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { RoleApi } from '#/api/system/role';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { Plus } from '@vben/icons';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { batchDeleteRoles, deleteRole, getRolePagedList, updateRole, getRoleById } from '#/api/system/role';
import { $t } from '#/locales';

import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    fieldMappingTime: [['createdTime', ['startTime', 'endTime']]],
    schema: useGridFormSchema(),
    submitOnChange: true,
  },
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    checkboxConfig: {
      checkField: 'checked',
      trigger: 'row',
      highlight: true
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getRolePagedList({
            pageIndex: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
      props: {
        result: 'items',
        total: 'totalCount'
      }
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
      zoom: true,
    },
  } as VxeTableGridOptions<RoleApi.RoleItem>,
});

function onActionClick(params: { code: string; row: RoleApi.RoleItem }) {
  switch (params.code) {
    case 'delete': {
      onDelete(params.row);
      break;
    }
    case 'edit': {
      onEdit(params.row);
      break;
    }
  }
}

/**
 * 编辑角色
 */
async function onEdit(row: RoleApi.RoleItem) {
  try {
    // 获取角色详情
    const detail = await getRoleById(row.id);
    // 打开抽屉并传入详情数据
    formDrawerApi.setData(detail).open();
  } catch (error) {
    console.error('获取角色详情失败:', error);
  }
}

function onDelete(row: RoleApi.RoleItem) {
  if (row.isSystem) {
    ElMessage.warning($t('system.role.systemRoleHint'));
    return;
  }

  ElMessageBox.confirm(
    $t('ui.actionMessage.deleteConfirm', [row.name]),
    $t('ui.actionTitle.delete', [$t('system.role.name')]),
    {
      confirmButtonText: $t('common.confirm'),
      cancelButtonText: $t('common.cancel'),
      type: 'warning',
    }
  )
    .then(() => {
      ElMessage({
        message: $t('ui.actionMessage.deleting', [row.name]),
        type: 'info',
      });

      deleteRole(row.id)
        .then(() => {
          ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
          onRefresh();
        })
        .catch(() => {
          ElMessage.error($t('ui.actionMessage.deleteFailed', [row.name]));
        });
    })
    .catch(() => {
      // 用户取消删除操作
    });
}

// 批量删除选中的角色
function onBatchDelete() {
  const selectedRows = gridApi.grid?.getCheckboxRecords() as RoleApi.RoleItem[] || [];
  if (!selectedRows || selectedRows.length === 0) {
    ElMessage.warning($t('common.actionMessage.selectRecords'));
    return;
  }

  // 检查是否包含系统角色
  const systemRoles = selectedRows.filter(row => row.isSystem);
  if (systemRoles.length > 0) {
    ElMessage.warning($t('system.role.systemRoleHint'));
    return;
  }

  const selectedIds = selectedRows.map(row => row.id);

  ElMessageBox.confirm(
    $t('system.role.batchDeleteConfirm'),
    $t('ui.actionTitle.batchDelete'),
    {
      confirmButtonText: $t('ui.actionButton.confirm'),
      cancelButtonText: $t('ui.actionButton.cancel'),
      type: 'warning',
    }
  )
    .then(() => {
      ElMessage({
        message: $t('ui.actionMessage.batchDeleting'),
        type: 'info',
      });

      batchDeleteRoles(selectedIds)
        .then(() => {
          ElMessage.success($t('system.role.batchDeleteSuccess', { count: selectedIds.length }));
          onRefresh();
        })
        .catch(() => {
          ElMessage.error($t('ui.actionMessage.batchDeleteFailed'));
        });
    })
    .catch(() => {
      // 用户取消删除操作
    });
}

function onRefresh() {
  gridApi.query();
}

function onCreate() {
  formDrawerApi.setData({}).open();
}

function onFormSuccess() {
  // 表单提交成功后刷新列表
  onRefresh();
}
</script>

<template>
  <Page auto-content-height>
    <FormDrawer @success="onFormSuccess" />
    <Grid :table-title="$t('system.role.list')">
      <template #toolbar-tools>
        <el-button type="primary" @click="onCreate">
          <Plus class="size-5" />
          {{ $t('ui.actionTitle.create', [$t('system.role.name')]) }}
        </el-button>
        <el-button type="danger" @click="onBatchDelete">
          <i class="el-icon-delete"></i>
          {{ $t('system.role.batchDelete') }}
        </el-button>
      </template>
    </Grid>
  </Page>
</template>
